package com.chen.glide_ex;

import android.support.annotation.NonNull;

import com.bumptech.glide.load.model.DataUrlLoader;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.MultiModelLoaderFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by chenjian on 2019/3/22 15:59.
 */
public final class OlyBase64StreamFactory<Model> implements ModelLoaderFactory<Model, InputStream> {

    private final DataUrlLoader.DataDecoder<InputStream> opener;

    public OlyBase64StreamFactory() {
        opener = new DataUrlLoader.DataDecoder<InputStream>() {
            @Override
            public InputStream decode(String uri) throws IllegalArgumentException {
                String prefix = "data:image";
                if (!uri.startsWith(prefix)) {
                    throw new IllegalArgumentException("Not a valid image data URL.");
                }

                byte[] bytes = Base64tUtil.decodeBase64(uri.substring(10));
                return new ByteArrayInputStream(bytes);
            }

            @Override
            public void close(InputStream inputStream) throws IOException {
                inputStream.close();
            }

            @Override
            public Class<InputStream> getDataClass() {
                return InputStream.class;
            }
        };
    }

    @NonNull
    @Override
    public ModelLoader<Model, InputStream> build(@NonNull MultiModelLoaderFactory multiFactory) {
        return new DataUrlLoader<>(opener);
    }

    @Override
    public void teardown() {
        // Do nothing.
    }
}
